package com.flyou.ccnucenter.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ListView;

import com.flyou.ccnucenter.R;

/**
 * ============================================================
 * 项目名称：HenuCenterPro
 * 包名称：com.flyou.flying.widget
 * 文件名：AutoLoadListView
 * 类描述：
 * 创建人：flyou
 * 邮箱：fangjaylong@gmail.com
 * 创建时间：2015/11/10 8:59
 * 修改备注：
 * 版本：@version  V1.0
 * ============================================================
 */
public class AutoLoadListView extends ListView implements AbsListView.OnScrollListener {
    private View footerView;//底部布局
    private int totalItemCount;//总数量
    private int firstVisableItem;
    private int lastVisableitem;//最后一个可见的条目
    private boolean isLoading;//正在加载
    private LoadMoreListener loadMoreListener;//加载更多的监听

    public AutoLoadListView(Context context) {
        this(context, null);
    }

    public AutoLoadListView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public AutoLoadListView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        ininView(context);
    }

    private void ininView(Context context) {

        LayoutInflater layoutInflater = LayoutInflater.from(context);
        footerView = layoutInflater.inflate(R.layout.autoload_listview_footer, null);
        footerView.findViewById(R.id.auto_listview_layout).setVisibility(GONE);

        isLoading = false;
        this.addFooterView(footerView, null, false);
        this.setOnScrollListener(this);

    }

    public void setLoadComplete() {
        footerView.findViewById(R.id.auto_listview_layout).setVisibility(GONE);
        isLoading = false;

    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        this.lastVisableitem = firstVisibleItem + visibleItemCount;
        this.totalItemCount = totalItemCount;
        this.firstVisableItem = firstVisibleItem;
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {

        Log.i("Main", lastVisableitem + ":" + totalItemCount);
        if (lastVisableitem  == totalItemCount && scrollState == SCROLL_STATE_IDLE) {

            if (!isLoading) {
                isLoading = true;
                footerView.findViewById(R.id.auto_listview_layout).setVisibility(VISIBLE);
                loadMoreListener.LoadMore();
            }
        }
    }

    public void setLoadMoreListener(LoadMoreListener loadMoreListener) {
        this.loadMoreListener = loadMoreListener;

    }

    public interface LoadMoreListener {
        public void LoadMore();
    }

}
